#!/usr/bin/python

import re, string, sys, httplib, urllib2, os
import MySQLdb, tagpot
from xml.dom import minidom

cursor = tagpot.dbConnect()

cursor.execute("""select anchor from anc order by id DESC""")
data = cursor.fetchall()

# get Video Info xml from YouTube 
def xmlAccess(id):
	APIURL = "http://www.youtube.com/api2_rest?method=youtube.videos.get_details&dev_id=ZyogdbWOQHc&video_id="
	request = urllib2.Request(APIURL+id)
	opener = urllib2.build_opener()
	info = ""
	info = opener.open(request).read()
	x = minidom.parseString(info)
	if x.getElementsByTagName("video_details"):
		return	x.getElementsByTagName("video_details")[0]
	else:
		return 'no'

def detailAccess(xml,i):
	return xml.getElementsByTagName(i)[0].firstChild.data

def literal(val):
	if val:
		val = val.replace("'", "^")
		val = "'" + val + "'"
		return val   	
	else:
		return "NULL"

for d in data:
	#try:
		# get Youtube ID
		#id = d[2].replace("http://www.youtube.com/v/","")
		#id = id.split('&')[0]
		id = d[0]

		# from YouTube
		xml = xmlAccess(id)
		if xml != 'no':
			
			tags_video = detailAccess(xml,"tags")
			count_video = detailAccess(xml, "rating_count")
			
			rating_avg = detailAccess(xml, "rating_avg")
			chList = xml.getElementsByTagName("channel_list")[0]
			# only first channel
			ch = detailAccess(chList, "channel")
			title = detailAccess(xml, "title")
			length = detailAccess(xml, "length_seconds")
			img = detailAccess(xml, "thumbnail_url")
			count_view = detailAccess(xml, "view_count")
			embed = detailAccess(xml, "embed_status")
			
			
			# tag formatting
			tags_video = tags_video.replace(" ", ",")
			
			# insert to table
			qu = "UPDATE anc SET en=%s, count='%s', rating_avg='%s', ch='%s', title=%s, length='%s', img='%s', count_view='%s', embed = '%s' where anchor='%s'" % (literal(tags_video), count_video, rating_avg, ch, literal(title), length, img, count_view, embed,id)
			cursor.execute(qu);
			
		else:
			qu = "UPDATE anc SET ok='0' where anchor='%s'" % (id)
			cursor.execute(qu);
			print "no video: "+id
		
	#except:
	#	continue
